#ifndef YHAIDA_TIMER_H
#define YHAIDA_TIMER_H
#include "../base/Utils.h"
#include "../datetime/Timestamp.h"
#include "Callbacks.h"
#include "../thread/Atomic.h"
namespace yhaida
{
    class Timer : Utils::nocapyable
    {
    public:
        Timer(TimerCallback func, Timestamp when, double Interval)
            : _Callback(std::move(func)),
              _TimeOfExpiration(when),
              _Interval(Interval),
              _isRepeat(Interval > 0.0),
              _sequence(_numCreated.incrementAndGet())
        {
        }
        ~Timer() = default;

        void handleCallback() const
        {
            _Callback();
        }

        Timestamp expiration() const
        {
            return _TimeOfExpiration;
        }

        bool isRepeat() const
        {
            return _isRepeat;
        }
        int64_t sequence() const { return _sequence; }
        void restart(Timestamp now)
        {
            if (_isRepeat)
            {
                _TimeOfExpiration = addTime(now, _Interval);
            }
            else
            {
                _TimeOfExpiration = Timestamp::invalid();
            }
        }

    private:
        const TimerCallback _Callback;
        Timestamp _TimeOfExpiration;
        const double _Interval;
        const bool _isRepeat;

        const int64_t _sequence;

        static AtomicInt64 _numCreated; //唯一
    };
    AtomicInt64 Timer::_numCreated;

}

#endif